package com.rv.common.core.util;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public final class RsaUtil {
    private static final String RSA = "RSA";
    private static final int KEY_SIZE = 512;

    public static KeyPair genKeyPair() throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
        kpg.initialize(KEY_SIZE);
        return kpg.generateKeyPair();
    }

    public static String decrypt(String base64Pri, String base64Cipher) throws Exception {
        PrivateKey pri = KeyFactory.getInstance(RSA)
                .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64Pri)));
        Cipher c = Cipher.getInstance(RSA);
        c.init(Cipher.DECRYPT_MODE, pri);
        byte[] plain = c.doFinal(Base64.getDecoder().decode(base64Cipher));
        return new String(plain, StandardCharsets.UTF_8);
    }
}